<template>
  <el-form label-width="80px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择SPU品牌">
        <el-option
          v-for="trademark in trademarkList"
          :key="trademark.id"
          :label="trademark.tmName"
          :value="trademark.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input :rows="2" type="textarea" placeholder="Please input" />
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="fileList"
        :action="`${BASE_URL}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-select
        :placeholder="`还有${filterBaseSaleAttrList.length}个未选择`"
        v-model="spuInfo.spuSaleAttr"
      >
        <el-option
          v-for="baseSale in filterBaseSaleAttrList"
          :key="baseSale.id"
          :label="baseSale.name"
          :value="baseSale.name"
        />
      </el-select>
      <el-button
        type="primary"
        :icon="Plus"
        @click="addSpuSaleAttr"
        :disabled="!spuInfo.spuSaleAttr"
        >添加销售属性</el-button
      >

      <el-table border :data="spuInfo.spuSaleAttrList" style="margin-top: 10px">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="属性名"
          prop="saleAttrName"
          width="100px"
        ></el-table-column>
        <!-- 这个是tag气泡 -->
        <el-table-column label="属性值列表">
          <template v-slot="{ row, $index }">
            <el-tag
              v-for="tag in row.spuSaleAttrValueList"
              :key="tag.id"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="handleClose(row, tag)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="ml-1 w-20"
              size="small"
              @keyup.enter="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showInput(row)"
            >
              + New Tag
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template v-slot="{ row, $index }">
            <el-popconfirm
              confirm-button-text="删除"
              cancel-button-text="取消"
              @confirm="deleteAttr"
              :icon="InfoFilled"
              icon-color="red"
              title="确定要删除该项信息吗?"
            >
              <template #reference>
                <el-button
                  :icon="Delete"
                  type="danger"
                  size="small"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary">保存</el-button>
      <el-button @click="getSceneValue">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "SpuForm",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive, computed, nextTick } from "vue";
import { Plus, Delete, InfoFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile, ElInput } from "element-plus";
import {
  reqGetAllTrademarkList,
  reqGetBaseSaleAttrList,
} from "@/api/product/spu";
// tag气泡属性
const inputValue = ref("");
const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
// 动态读取环境变量中的值
const BASE_URL = import.meta.env.VITE_API_URL;
// 表单校验参数
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

// 声明变量存储数据
// 定义两个变量 来存储品牌列表和基础销售属性
const trademarkList = ref([]);
const baseSaleAttrList = ref([]);

// 存储照片墙数组
const fileList = [];
// const imageUrl = ref("");
// 自定义事件
const emits = defineEmits(["changeValue"]);

// // 定义一个存储spu相关数据的变量
const spuInfo = reactive({
  spuName: "", // spu的名称
  tmId: "", // spu品牌
  description: "", // spu描述
  spuImageList: [], // 存储spu图片的数组
  spuSaleAttrList: [], // 基本销售属性
  spuSaleAttr: "", // 收集选中的属性 颜色 版本  尺寸
  category3Id: "", // 三级id
});

// 删除图片执行函数
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  spuInfo.spuImageList = uploadFiles;
};

// 图片预览时要执行的函数
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  // 上传之前对图片的校验
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 上传成功后要执行的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // 将添加的照片存储到照片数组中 数组存储的是对象
  spuInfo.spuImageList.push({
    imgName: uploadFile.name,
    imgUrl: response.data,
  });
};

// 上传之前要执行的函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgTypes = ["image/jpeg", "image/png", "image/jpg", "image/jfif"];
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error("上传照片把格式不正确");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("请传入大小小于2M的照片");
    return false;
  }
  return true;
};

// 6. 添加基础销售属性 Form表单添加属性按钮
const addSpuSaleAttr = () => {
  const spuSaleAttrList = spuInfo.spuSaleAttrList;
  // 如果下拉框中没有属性可以添加了,而且属性表格中还有空的属性值不能继续添加
  if (
    spuSaleAttrList.length &&
    spuSaleAttrList.some((item) => item.spuSaleAttrValueList.length == 0)
  ) {
    ElMessage.error("属性值不能为空,请添加属性");
    return;
  }
  spuInfo.spuSaleAttrList.push({
    // 属性名
    saleAttrName: spuInfo.spuSaleAttr, // 属性名 颜色 版本  尺寸
    // 属性值数组
    spuSaleAttrValueList: [],
    // 传递对象时让输入框默认消失
    inputVisible: false,
  });
  // 清空一下下拉框
  spuInfo.spuSaleAttr = "";
};

// 7.计算属性实现属性的互斥
const filterBaseSaleAttrList = computed(() => {
  return baseSaleAttrList.value.filter((baseSale) => {
    return !spuInfo.spuSaleAttrList.find((item) => {
      return item.saleAttrName === baseSale.name;
    });
  });
});

// 8.删除baseSaleAttrList数组中的一条数据
// 清除当前属性
const deleteAttr = (index: number) => {
  spuInfo.spuSaleAttrList.splice(index, 1);
};

// 9.添加属性value的数组  以下三个函数是Tag里面的狗子函数
const handleClose = (row: any, tag: any) => {
  // 查找tag所在数组中的索引值
  row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1);
};

const showInput = (row: any) => {
  row.inputVisible = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

// 添加气泡标签的函数
const handleInputConfirm = (row: any) => {
  if (inputValue.value) {
    const spuSaleAttrValueList = row.spuSaleAttrValueList;
    if (
      spuSaleAttrValueList.length &&
      spuSaleAttrValueList.find(
        (item) => item.saleAttrValueName == inputValue.value
      )
    ) {
      ElMessage.error("属性有重复,请勿重复添加相同属性");
      row.inputVisible = false;
      inputValue.value = "";
      return;
    }

    row.spuSaleAttrValueList.push({
      saleAttrName: row.saleAttrName, // 当前属性名称 比如 颜色 版本 尺寸
      saleAttrValueName: inputValue.value, // 具体的属性值
    });
  }
  row.inputVisible = false;
  inputValue.value = "";
};

// 返回列表页面
// 给按钮添加事件
function getSceneValue() {
  emits("changeValue", 1);
}

//组件挂载时发送请求获取整个页面数据
onMounted(async () => {
  try {
    const [responseTrademarkList, responseBaseSaleAttrList] = await Promise.all(
      [reqGetAllTrademarkList(), reqGetBaseSaleAttrList()]
    );
    // console.log("aw", responseTrademarkList, responseBaseSaleAttrList);
    trademarkList.value = responseTrademarkList;
    baseSaleAttrList.value = responseBaseSaleAttrList;
    // console.log(trademarkList.value);
    // console.log("spu属性", baseSaleAttrList.value);
  } catch (error) {
    ElMessage.error("获取品牌或属性失败...");
  }
});
</script>

<style>
</style>